//
//  ORSearchView.m
//  OR_1
//
//  Created by Luboš Kulič on 9/30/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//
//  28411391

#import "ORSearchView.h"
#import "DataItem.h"
#import "ORDataItems.h"
#import "XMLParser.h"

@interface ORBasicInfoView (ORBasicInfoViewPrivs) 
//-(NSInteger) numberOfSectionsInComplexItem:(ComplexDataItem*) dataItem;
//-(NSInteger) tableViewNumberOfRowsInSection:(NSInteger)section inComplexItem:(ComplexDataItem*) dataItem;
//-(UITableViewCell *) tableViewCellForRowAtIndexPath:(NSIndexPath *)indexPath inComplexItem:(ComplexDataItem*) dataItem;
//
//-(NSInteger) numberOfSectionsInSimpleItem:(SimpleDataItem*) dataItem;
//-(NSInteger) tableViewNumberOfRowsInSection:(NSInteger)section inSimpleItem:(SimpleDataItem*) dataItem;
//-(UITableViewCell *) tableViewCellForRowAtIndexPath:(NSIndexPath *)indexPath inSimpleItem:(SimpleDataItem*) dataItem;
//
//-(NSInteger) numberOfSectionsInArrayItem:(ArrayDataItem*) dataItem;
//-(NSInteger) tableViewNumberOfRowsInSection:(NSInteger)section inArrayItem:(ArrayDataItem*) dataItem;
//-(UITableViewCell *) tableViewCellForRowAtIndexPath:(NSIndexPath *)indexPath inArrayItem:(ArrayDataItem*) dataItem;

/// Defines order of particular elements in a view
-(id) indexForDataElement:(DataItem *) data andRowNum:(NSUInteger) row ;
-(id) descriptionIndexForDataElement:(DataItem *) data andRowNum:(NSUInteger) row ;
-(id) indexForDataElement:(DataItem *) data andRowNum:(NSUInteger) row descriptionIndex:(BOOL) desc ;

// K cemu???
/// Returns list of index names for given element type
-(NSArray *) indexListForDataELement:(DataItem *) data;

@end


/// 2D dictionary/array:
/// key1 = item type, val = array of item names (indexed by position)
NSMutableDictionary * complexItemsLayout;

// TODO - some possibility to inherit description from subelements - maybe by creating a path of element names
// i.e. description for Vypis_OR with index 1 == ->D:ZAU->D:OF

NSMutableDictionary * complexItemsDescriptionLayout;


@implementation ORBasicInfoView

+(void) initialize {
	complexItemsLayout = [[NSMutableDictionary dictionary] retain];
	complexItemsDescriptionLayout = [[NSMutableDictionary dictionary] retain];
	
	// TODO - constants for XML elements
	// init data layout
	NSArray * layout = 
			[NSArray arrayWithObjects:
			  @"D:ZAU"
			 ,@"D:CIN"
			 ,@"D:SO", @"D:SOP"
			 ,NULL	
			  ];
	
	[complexItemsLayout setObject:layout forKey:@"D:Vypis_OR"];
	
	layout = 
			[NSArray arrayWithObjects:
			 @"D:OF"
			 ,@"D:ICO"			 
			 ,@"D:SI"
			 ,NULL	
			 ];
	
	[complexItemsLayout setObject:layout forKey:@"D:ZAU"];

	// TODO: enable possibility to combine more items into one line (with whitespace...)
	layout = 
			[NSArray arrayWithObjects:
			 @"D:NU" // ulice
			 ,@"D:CD" // cislo domu
			 ,@"D:N" // nazev obce
			 ,@"D:PSC"
			 ,NULL	
			 ];
	
	[complexItemsLayout setObject:layout forKey:@"D:SI"];
	
	[complexItemsDescriptionLayout setObject:layout forKey:@"D:SI"];
	
	/*
	@"D:Vypis_OR"
	,@"D:ZAU" // zakladni udaje
	,@"are:Zaznam"			
	,@"D:C" /
	 
	 @"D:CIN" // cinnosti	
	 ,@"D:SO", @"SOP" 
	 */
	
}

-(void)initData:(DataItem *) data_ {
	[data autorelease];
	data = [data_ retain];
}


-(id) indexForDataElement:(DataItem *) data andRowNum:(NSUInteger) row  {
	return [self indexForDataElement:data andRowNum:row descriptionIndex:FALSE];
}

-(id) descriptionIndexForDataElement:(DataItem *) data andRowNum:(NSUInteger) row  {
	return [self indexForDataElement:data andRowNum:row descriptionIndex:TRUE];
}


-(id) indexForDataElement:(DataItem *) data andRowNum:(NSUInteger) row descriptionIndex:(BOOL) desc {
	NSString * itemType = [data itemType];
	if (!itemType || itemType == DataItemTypeSimple) {
		return [NSNumber numberWithInt:1];
	} else if (itemType == DataItemTypeArray) {
		return [NSNumber numberWithInt:row]; // only description for Array item is its name - regardless of the index
	} else {
		NSDictionary * dictionary = desc ? complexItemsDescriptionLayout : complexItemsLayout;
		NSArray * ar = [dictionary objectForKey:itemType];
		if(ar && row < [ar count]) {
			return [ar objectAtIndex:row ];
		} else {
			return 0;
		}
	}
	
}


-(NSArray *) indexListForDataELement:(DataItem *) data {
	NSString * itemType = [data itemType];
	if (!itemType || itemType == DataItemTypeSimple || itemType == DataItemTypeArray) {
		return 0;
	} else {
		return [complexItemsLayout objectForKey:itemType];		
	}
}

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
	NSLog(@"Number of sections:");
	
	// test
	//DataItem *complexItem = [ORComplexItem alloc];
	//DataItem *simpleItem = @"Simple test string";
	//DataItem *arrayItem = [[NSMutableArray array] retain];
		
	//NSLog(@"Trying complex item:", [complexItem numberOfValues]);
	
	//NSLog(@"Trying simple item:", [simpleItem numberOfValues]);
	NSLog(@"Actual data: %@", data);
	
	return [data numberOfValues];
}


-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
	NSLog(@"Number of rows");
	return [[data valueWithIndex:[self indexForDataElement:data andRowNum:section]] numberOfDescriptionItems];
}


-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	// !!!!!!!!!!!!!!!!!!!!!!!!!!
	// TODO
	
	// prelozit cislo indexu a jmeno data elementu (=typ=jmeno XML elementu)
	// na konkretni jmeno podelementu (-> datova struktura mi pak pro jmeno vrati jen hodnotu, nemusi se starat o to,
	// kolikata na strance ma byt ktera hodnota
	
	// !!!!!!!!!!!!!!!!!!!!!!!!!!
	
	
	NSLog(@"Get Cell");
	
	static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
	NSLog(@"Table cell");
	
	DataItem * tmpItem;
	
	NSString * content = [(tmpItem = [data valueWithIndex:[self indexForDataElement:data andRowNum: indexPath.section]]) 
				  descriptionWithIndex:[self indexForDataElement:tmpItem andRowNum:indexPath.row]
				  ];
	
    cell.textLabel.text = content;// TODO something like content.textContent (content is DataItem*)
	
	//cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ %@ %@"
//								 , [array objectAtIndex:indexPath.row]
//								 , [array objectAtIndex:indexPath.row]
//								 , [array objectAtIndex:indexPath.row]
//								 ];
	///cell. = @"blablabla";
	
    
    return cell;
	
}

- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	return [self indexForDataElement:data andRowNum:section];
}




//-(NSInteger) numberOfSectionsInComplexItem:(ComplexDataItem *) dataItem{
//	
//}
//
//-(NSInteger) tableViewNumberOfRowsInSection:(NSInteger)section inComplexItem:(ComplexDataItem *) dataItem{
//	
//}
//
//-(UITableViewCell *) tableViewCellForRowAtIndexPath:(NSIndexPath *)indexPath inComplexItem:(ComplexDataItem *) dataItem{
//	
//}
//
//// ------------------------------------------
//
//
//-(NSInteger) numberOfSectionsInSimpleItem:(SimpleDataItem *) dataItem{
//	
//}
//
//-(NSInteger) tableViewNumberOfRowsInSection:(NSInteger)section inSimpleItem:(SimpleDataItem*) dataItem{
//	
//}
//
//-(UITableViewCell *) tableViewCellForRowAtIndexPath:(NSIndexPath *)indexPath inSimpleItem:(SimpleDataItem*) dataItem{
//	
//}
//
//// ------------------------------------------
//
//
//-(NSInteger) numberOfSectionsInArrayItem:(ArrayDataItem*) dataItem{
//	
//}
//
//-(NSInteger) tableViewNumberOfRowsInSection:(NSInteger)section inArrayItem:(ArrayDataItem*) dataItem{
//	
//}
//
//-(UITableViewCell *) tableViewCellForRowAtIndexPath:(NSIndexPath *)indexPath inArrayItem:(ArrayDataItem*) dataItem{
//	
//}

// ------------------------------------------



@end


@interface ORSearchView (ORSearchViewPrivs) 
-(void) searchBarHide:(UISearchBar *)searchBar;
@end



@implementation ORSearchView


@synthesize navigationBar;
//@synthesize searchResults;
@synthesize orSearch;
@synthesize bottomToolbar;
@synthesize actualAllSwitch;

@synthesize basicInfoView;
@synthesize activityIndicator;




-(IBAction)processSearch:(id)sender {
	//	Network * net = [[Network alloc] init];
		
}



-(void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
	[searchBar setShowsCancelButton:YES animated:YES];	
}


-(void) searchBarHide:(UISearchBar *)searchBar {
	[searchBar setShowsCancelButton:NO animated:YES];
	
	[searchBar resignFirstResponder];
	
}

-(void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
	NSLog(@"Cancel clicked");
	[self searchBarHide:searchBar];
}

-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
	NSLog(@"Search clicked");
	
	[self searchBarHide:searchBar];
	[activityIndicator startAnimating];
	
	NSLog(@"Processing search...");
	
	NSString * query = [searchBar.text retain];	
	
//  28411391
	
	if (query != NULL && ![query isEqualToString:@""] ) {
		
		//---  TODO  ---//
		
		// je ares inicializovany?
		
		// detect if it is ICO or company name
		if( [query intValue] ) {
			// try ico
			NSLog(@"Int value");
			//[ares searchForCompany:0 orID:query notifyEnd:self];
			[ares searchInORfor:query notifyEnd:self];
		} else {
			// try company name
			NSLog(@"String value");
			[ares searchForCompany:query orID:0 notifyEnd:self];			 
		}
		
		//[ares searchInORfor:query notifyEnd:self];
		// je to tady v tom volani!!! 
		

	} else {
		[activityIndicator stopAnimating];
	}
	
	[query autorelease];
	
	
	
	
	NSLog(@"End method processSearch");
	
}

-(void) ARES:(ARES *)ares didFinishSearchWithResult:(NSData *)data {
	
	NSLog(@"Received answer: %@", [NSString stringWithUTF8String:[data bytes]]);
		
	ORDataItem * text = [[parser parse:data] retain];
	
	
	//NSLog(@"Result: %@", [text->basicInfo description]);
	
	[basicInfoView initData:[text autorelease]];
	
	[basicInfoView.tableView reloadData];
	
	[activityIndicator stopAnimating];
	
	NSLog(@"End query processing");
}





/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	ares = [[ARES alloc] init];
	parser = [[XMLParser alloc] init];
	
	
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
